import { createRouter, createWebHashHistory } from "vue-router";
import Layout from "@/components/layout/LayoutIndex.vue";
import db from "@/utils/db";

const routes = [
  {
    path: "/",
    redirect: "/system/user",
  },
  {
    path: "/",
    name: "layout",
    component: Layout,
    children: [
      {
        path: "/system/user",
        name: "user",
        meta: {
          title: "用户管理",
        },
        component: () => import("@/views/system/User.vue"),
      },
      {
        path: "/system/role",
        name: "role",
        meta: {
          title: "角色管理",
        },
        component: () => import("@/views/system/Role.vue"),
      },
      {
        path: "/system/menu",
        name: "menu",
        meta: {
          title: "菜单管理",
        },
        component: () => import("@/views/system/Menu.vue"),
      },
      {
        path: "/system/dept",
        name: "dept",
        meta: {
          title: "部门管理",
        },
        component: () => import("@/views/system/Dept.vue"),
      },
      {
        path: "/:catchAll(.*)",
        name: "404",
        meta: {
          title: "找不到页面",
        },
        component: () => import("@/views/error/404"),
      },
      {
        path: "/403",
        name: "403",
        meta: {
          title: "没有权限",
        },
        component: () => import("@/views/error/403"),
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    meta: {
      title: "登录",
    },
    component: () => import("@/views/system/Login.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  document.title = to.meta.title;

  const userInfo = db.get("userInfo");
  const token = db.get("token");

  if (!token && to.path !== "/login") {
    next("/login");
  }
  if (
    userInfo.role &&
    userInfo.role.indexOf("管理员") === -1 &&
    !to.path.startsWith("/login") &&
    !to.path.startsWith("/403")
  ) {
    next("/403");
  } else {
    next();
  }
});

export default router;
